import { Component, OnInit, Input } from '@angular/core';
import { ActivatedRoute, Router, Params } from '@angular/router';

import { CommentService } from '../services/comment.service';
import { Comment } from '../model/comment-model';
import {User} from "../../user/model/user-model";
import { Http, Response, Headers, RequestOptions,URLSearchParams } from '@angular/http';

@Component({
  selector: 'app-add-comment',
  templateUrl: './add-comment.component.html',
  styleUrls: ['./add-comment.component.scss']
})
export class AddCommentComponent implements OnInit {
  public comments: Array<Comment>;
  public currentUser:User= JSON.parse(localStorage.getItem("currentUser"));
  public comment:Comment = new Comment();
  public postId:number;

  constructor(
    public commentService: CommentService,
    public activeRoute: ActivatedRoute,
    public router:Router,
    public http:Http)
  {

  }

  ngOnInit() {
    this.activeRoute.params.subscribe(
      params => {
        this.postId = params["postId"];
        this.getCommentList(this.postId);
      }
    );
  }

  public getCommentList(postId: number){
    this.commentService.getCommentList(postId)
      .subscribe(
        data => {
          this.comments = data;
        },
        error => console.error(error)
      );
  }

  addComment(){
    this.comment.date = new Date();
    this.comment.author = this.currentUser.userName;
    this.comment.postId = this.postId;
    console.log(this.comment);
    this.http.post('http://localhost:3000/posts/addComment',this.comment)
      .subscribe(data=>{
        this.ngOnInit();
      });

  }
}
